<template>
  <div class="bigbox">
    <!-- 页面头部搜索栏 -->
    <div class="topbox" :style="{height:isheight+'px'}">
      <el-form :model="form" ref="form"  label-position="left" label-width="80px" onsubmit="return false">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="用电企业">
              <!-- <el-select v-model="form.orgNo" style="width: 100%;" size="small" filterable ref="qiye" @change="changeqiye">
                <el-option v-for="(item,index) in qiyelist" :key="index" :label="item.bizOrgName" :value="item.bizOrgNo" class="option"></el-option>
              </el-select> -->
              <FilterSelect2
                      v-model="form.orgNo"
                      @updateModelValue="changeqiye"
                      :optionlist="qiyelist"
                      :valuekey="{ name: 'bizOrgName', value: 'bizOrgNo' }"
                    ></FilterSelect2>
            </el-form-item>
          </el-col> 
          <el-col :span="6" style="display: flex;margin-top: 4px;">
              <el-radio-group v-model="radio3" size="small" style="margin-right: 20px;">
                <el-radio-button label="日"></el-radio-button>
                <el-radio-button label="月"></el-radio-button>
                <el-radio-button label="年"></el-radio-button>
              </el-radio-group>
              <template v-if="radio3=='日'">
                <el-date-picker
                size="small"
                  v-model="value1"
                  style="flex: 1;"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日">
                </el-date-picker>
              </template>
              <template v-else-if="radio3=='月'">
                <el-date-picker
                size="small"
                  v-model="value2"
                  value-format="yyyy-MM"
                  style="flex: 1;"
                  type="month"
                  placeholder="选择月">
                </el-date-picker>
              </template>
              <template v-else>
                <el-date-picker
                size="small"
                  v-model="value3"
                  value-format="yyyy"
                  style="flex: 1;"
                  type="year"
                  placeholder="选择年">
                </el-date-picker>
              </template>
          </el-col>
          <el-col :span="5">
            <el-form-item label="配电室">
              <!-- <el-select v-model="form.switchroomId" style="width: 100%;" size="small" @change="changepei">
                <el-option v-for="(item,index) in peidianlist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
              </el-select> -->
              <FilterSelect2
                      v-model="form.switchroomId"
                      @updateModelValue="changepei"
                      :optionlist="peidianlist"
                      :valuekey="{ name: 'name', value: 'id' }"
                    ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="设备">
              <!-- <el-select v-model="form.bayId" style="width: 100%;" size="small" @change="changeshebei">
                <el-option v-for="(item,index) in shebeilist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
              </el-select> -->
              <FilterSelect2
                      v-model="form.bayId"
                      @updateModelValue="changeshebei"
                      :optionlist="shebeilist"
                      :valuekey="{ name: 'name', value: 'id' }"
                    ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="3" style="text-align: right !important;margin-top: 4px;">
              <el-button  size="small">重 置</el-button>
              <el-button  size="small" type="primary" @click="submit">查 询</el-button>
              <!-- <button type="button" v-if="isshow" class="shou" @click="zedie">收起 <i class="el-icon-arrow-up"></i> </button>
              <button type="button" v-else class="shou" @click="zedie">展开 <i class="el-icon-arrow-down"></i> </button> -->
        </el-col>
        </el-row>
        </el-form>
    </div>
    <!-- 盒子主体 -->
    <!-- <div class="bodybox" :style="{height: `calc(${num}% - ${number}px)`}"> -->
    <div class="bodybox" >
      <!-- 封装导出/刷新/调节功能 -->
      <div style="display: flex; justify-content: space-between;">
        <div>设备负荷分析</div>
        <div><TopTitle @command="command" @daochu="daochu" @shuaxin="shuaxin"></TopTitle></div>
      </div>
      <!-- 图表盒子 -->
      <div class="tubiaobox">

        <div class="zexian" ref="zexian"></div>
      </div>
      <!-- 表格盒子 -->
      <div class="tablebox">
        <template>
              <el-table
                :data="tableData"
                border
                highlight-current-row
                @current-change="handleCurrentChange"
                ref="table"
                :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
                v-loading="loading"
                :size="iissize"
                height="calc(100% - 1px)"
                style="width: 100%">
                <el-table-column
                  
                width="200"
                prop="devName"
                label="用电企业">
                </el-table-column>
                <template v-if="dayyearmonth=='日'">
                  <el-table-column
                  v-for="(item,index) in timeArray"
                  :key="index"
                  :prop="'load'+(index+1)"
                  :label="item"
                  align="right">
                </el-table-column>
                </template>
                <template v-else-if="dayyearmonth=='月'">
                  <el-table-column
                  v-for="(item,index) in montharr"
                  :key="index"
                  :prop="'load'+(index+1)"
                  :label="item.toString()"
                  align="right">
                </el-table-column>
                </template>
                <template v-else-if="dayyearmonth=='年'">
                  <el-table-column
                  v-for="(item,index) in monthArray"
                  :key="index"
                  :prop="'load'+(index+1)"
                  :label="item"
                  align="right">
                </el-table-column>
                </template>
              </el-table>
            </template>
      </div>
    </div>
  </div>
</template>

<script>
import { saveAs } from 'file-saver'
import { getuserlistapi ,getshebeifuheapi,exportfuheapi} from '@/api/analysis'
import TopTitle from '@/components/TopTitle/index.vue'
import * as echarts from 'echarts';
import { timeArray, getDaysInMonth, monthArray } from '@/utils/array'
import {geipeidiansapi,getshebeiapi} from '@/api/keynote'
export default {
  name: 'CallPoliceIndex',
  components: {
    TopTitle
  },
  data() {
    return {
      loading:false,
      isshow: false,
      number:90,
      num:100,
      qiyelist: [],
      shebeilist:[],
      peidianlist: [],
      tableData:[],
      iissize: 'medium',
      value1: '',
      value2: '',
      value3:'',
      radio3: '日',
      form: {switchroomName:'',bayName:'',bayId:''},
      isheight: '80',
      dayyearmonth: '日',
      timeArray: timeArray,
      monthArray: monthArray,
      echartarray:[]
    };
  },

  async mounted() {
    this.gettime()
    this.getmonth()
    const res = await getuserlistapi()
    this.qiyelist = res.data.list
    this.form.orgNo=this.$store.state.statistics.userbizOrgNo ? this.$store.state.statistics.userbizOrgNo : res.data.list[0].bizOrgNo
    await this.getpeidianxiala(this.form.orgNo)
    this. getdatalist()
    this.getzheecharts()
  },

  methods: {
    // 查询
    submit() {

      this.dayyearmonth = this.radio3
      this.getdatalist()
      this.getzheecharts()
    },
    // 获取表格数据
    async getdatalist() {
      if (!this.form.switchroomId) return this.$message.warning('配电室不可为空')
      this.loading=true
      const res = await getshebeifuheapi({
        ...this.form,
        periodType: this.radio3 == '日' ? 'day' : this.radio3 == '月' ? 'month' : 'year',
        dateStr:this.radio3 == '日' ? this.value1 : this.radio3 == '月' ? this.value2 : this.value3,
      })
      this.loading = false
        this.tableData = res.data.list
      this.$refs.table.setCurrentRow(this.tableData[0]);
    },
    // 表格点击事件
    handleCurrentChange(val) {
      if (val) {
        const { switchroomName, devName, devId, ...obj } = val
        if (!Object.keys(obj).length) return this.echartarray = []
        const valuesArray = [];
        for (let i = 1; i < 97; i++) {
            const key = 'load' + i;
            valuesArray.push(obj[key]);
        }
      this.echartarray = valuesArray
      } else {
        this.echartarray=[]
      }
      this.getzheecharts()
    },
    // 刷新列表
    shuaxin() {
      this.getdatalist()
      this.$message.success('列表刷新成功')
     },
    // 导出功能
    async daochu() { 
      const orgName=this.qiyelist.filter(ele=>ele.bizOrgNo==this.form.orgNo)[0].bizOrgName
      const res = await exportfuheapi({
        ...this.form,
        orgName:orgName,
        periodType: this.radio3 == '日' ? 'day' : this.radio3 == '月' ? 'month' : 'year',
        dateStr: this.radio3 == '日' ? this.value1 : this.radio3 == '月' ? this.value2 : this.value3,
        isParams: true
      })
      const blobContent = new Blob([res])
      let url = window.URL.createObjectURL(blobContent)
      saveAs(url, '设备负荷分析.xls')
    },
    // 获取配电室下拉
    async getpeidianxiala(id) {
      const res = await geipeidiansapi({ orgNo: id })
      this.peidianlist = res.data.list
      this.form.switchroomId = res.data.list[0]?.id
      this.form.switchroomName=this.peidianlist.filter(ele=>ele.id == this.form.switchroomId)[0]?.name
      if (this.form.switchroomId) {
        this.getshebeixiala(res.data.list[0]?.id)
      } else {
        this.shebeilist = []
        this.form.bayId = ' '
        this.form.bayName=''
      }
    },
    // 获取设备下拉
    async getshebeixiala(id) {
      const res = await getshebeiapi({orgNo: this.form.orgNo, pathId: id })
      this.shebeilist = res.data.list
      this.shebeilist.unshift({name:'全部',id:''})
       this.form.bayId = res.data.list[0].id
      this.form.bayName = res.data.list.filter(ele => ele.id == this.form.bayId)[0].name
    },
       // 企业下拉框选择
    changeqiye(val) {
      this.$store.commit('setuserobject', val)
      this.getpeidianxiala(val)
      this.$forceUpdate()
    },
    // 配电室下拉
    changepei(val) {
      this.getshebeixiala(val)
      this.form.switchroomName=this.peidianlist.filter(ele=>ele.id == val)[0]?.name
    },
    // 设备下拉
    changeshebei(val) {
      this.form.bayName = this.shebeilist.filter(ele=>ele.id==val)[0].name
    },
    // 调节表格密度
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    zedie() {
      this.isshow = !this.isshow
      if (this.isshow) {
        this.isheight = 140
        this.number=150
      } else {
        this.isheight = 80
        this.number=90
      }
    },
// 获取当前时间戳
   gettime() {
      const date = new Date()
      const year = date.getFullYear() // 年
      const month = date.getMonth() + 1 // 月
      const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      this.value1 = year + '-' + month + '-' + day
      this.value2 = year + '-' + month
     this.value3 = year.toString()
    },
        // 获取当前选中的月份的日期
    getmonth() {
      const arr= this.value2.split('-')
    const daysInMonth = getDaysInMonth(arr[0], arr[1]);
    const numericDaysInMonth = daysInMonth.map(date => date.getDate()+'号');
      this.montharr = numericDaysInMonth
    },
    // 获取折线图
    getzheecharts() {
      var chartDom = this.$refs.zexian
      var myChart = echarts.init(chartDom);
      var option;
      option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data:this.dayyearmonth=='日'?timeArray:this.dayyearmonth=='月'?this.montharr:this.monthArray
        },
        yAxis: {
          name:'(kW)',
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        },
        grid:{ // 让图表占满容器
           top:"15%",
          left:"4%",
          right:"2%",
          bottom:"15%"
        },
        series: [
          {
            name: '负荷',
            smooth: true,
            type: 'line',
            data: this.echartarray,
            markPoint: {
              data: [
                { type: 'max', name: 'Max' },
                { type: 'min', name: 'Min' }
              ]
            },
            areaStyle: {
              normal: {
                //前四个参数代表位置 左下右上，如下表示从上往下渐变色 暗青色到亮青色，
                color: new echarts.graphic.LinearGradient(
                  0, 0, 0, 1,
                  [
                    { offset: 0, color: 'skyblue' },
                    { offset: 1, color: '#fff' }
                  ]
                )
              }
            },
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            }
          }
        ]
      };
      option && myChart.setOption(option);
    //   window.addEventListener("resize", () => {
    // //图表响应处理
    //     myChart.resize();
    //   });
      const resizeOb = new ResizeObserver((entries) => {
          for (const entry of entries) {
          echarts.getInstanceByDom(entry.target).resize();
        }
      });
        resizeOb.observe(this.$refs.zexian);
    }
  },
};
</script>

<style lang="scss" scoped>
.option{
  padding-left: 10px;
}
.bigbox{
  background-color:#f1f1f1;
  padding:10px;
  height:100%;
  
  .topbox{
      background-color: #fff;
      padding: 20px;
    }
  .bodybox{
    margin-top: 10px;
    // height: calc(100% - 90px);
    height: 800px;
    background-color: #fff;
    padding: 20px;
    .tubiaobox{
      height: 42%;
      margin-bottom: 15px;
      .zexian{
        height:100%;
      }
    }
    .tablebox{
      // margin-top: 15px;
      height: 50%;
      // height: 500px;
    }
  }
}
.bodybox{
  background-color: #fff;
  margin-top: 10px;
  padding: 20px 20px 20px 30px;
}
// ----------
</style>